package com.dmooo.ymx.fragments;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dmooo.ymx.MainActivity;
import com.dmooo.ymx.activity.SysMessageActivity;
import com.dmooo.ymx.bean.BannerBean;
import com.dmooo.ymx.utils.AutoHeightViewPager;
import com.dmooo.ymx.utils.CornerTransform;
import com.dmooo.ymx.utils.MyScrollView;
import com.dmooo.ymx.utils.VerticalViewPager;
import com.dmooo.ymx.utils.ViewPagerForScrollView;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.dmooo.ymx.R;
import com.dmooo.ymx.adapter.MyPagerAdapter;
import com.dmooo.ymx.base.BaseLazyFragment;
import com.dmooo.ymx.bean.Response;
import com.dmooo.ymx.common.CommonUtils;
import com.dmooo.ymx.common.SPUtils;
import com.dmooo.ymx.config.Constants;
import com.dmooo.ymx.https.HttpUtils;
import com.dmooo.ymx.https.onOKJsonHttpResponseHandler;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;
import androidx.annotation.RequiresApi;
import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;


/**
 * <pre>
 *     author : Administrator
 *     e-mail : szp
 *     time   : 2020/05/19
 *     desc   :
 *     version: 1.0
 * </pre>
 */

public class ReadFragmentNew extends BaseLazyFragment {
//    @BindView(R.id.swipe)
//    SwipeRefreshLayout swipeRefreshLayout;
    @BindView( R.id.mTb )
    TabLayout mTb;
//    @BindView( R.id.scrollview )
//    ScrollView scrollview;
    @BindView( R.id.mVp )
    ViewPager mVp;
    @BindView( R.id.main_banner )
    Banner banner;
    @BindView( R.id.tv_right )
    TextView tv_right;
    @BindView( R.id.read_layout )
    LinearLayout read_layout;

    private int ItemWhat=0;

    private LinearLayout headLayout;

    private List<BannerBean> images = new ArrayList<>();

    private List<Fragment> mFragmentList;
    private List<String> mTitleList;
    //设置界面文件和文字一一对应
    private Fragment[] Lfragments = {new NewsFragment()};
    private String[] Ltitles = {"新闻"};


    @Override
    protected void lazyload() {
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate( R.layout.activity_hyzx, container, false );
        ButterKnife.bind( this, view );
//        初始化监听
        getBanner();
        initListener();
        //添加标题
        initTitile();
        //添加fragment
//        initFragment();
//        mVp.setAdapter(new MyPagerAdapter(getActivity().getSupportFragmentManager(), mFragmentList, mTitleList));
//        //将tablayout与fragment关联
//        mTb.setupWithViewPager(mVp);

        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setIndicatorGravity(BannerConfig.RIGHT);
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
//                if (context != null && !((Activity) context).isDestroyed())
                    Glide.with(context).load(path).asBitmap().skipMemoryCache(false).dontAnimate().error(R.drawable.no_banner).transform(new CornerTransform(context, 10)).into(imageView);
            }

        });
//        if("#FFFFFF".equals(SPUtils.getStringData(getActivity(),"color","#FF3366"))){
//
//        }else{
//            read_layout.setBackgroundColor(Color.parseColor(SPUtils.getStringData(getActivity(),"color","#FF3366")));
//        }
        return view;
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initTitile() {
//        mTitleList = new ArrayList<>();
//        mTitleList.add("新闻");
//        mTitleList.add("生活");
//        mTitleList.add("健康");
//        mTitleList.add("公益");
        //设置tablayout模式
//        mTb.setTabMode(TabLayout.MODE_FIXED);
//        //tablayout获取集合中的名称
//        mTb.addTab(mTb.newTab().setText(mTitleList.get(0)));
//        mTb.addTab(mTb.newTab().setText(mTitleList.get(1)));
//        mTb.addTab(mTb.newTab().setText(mTitleList.get(2)));
//        mTb.addTab(mTb.newTab().setText(mTitleList.get(3)));

//        scrollview.setOnScrollChangeListener(new View.OnScrollChangeListener() {
//            @Override
//            public void onScrollChange(View view, int i, int i1, int oldX, int oldY) {
//                if (y >= topHeight) {
//                    //重点 通过距离变化隐藏内外固定栏实现
//                    llOutsideFixed.setVisibility(View.VISIBLE);
//                    insideFixedBar.setVisibility(View.GONE);
//                    recyclerView.setNestedScrollingEnabled(true);
//                } else {
//                    llOutsideFixed.setVisibility(View.GONE);
//                    insideFixedBar.setVisibility(View.VISIBLE);
//                    recyclerView.setNestedScrollingEnabled(false);
//                }
//            }
//        });
//        scrollview.setScrollChangeListener(new MyScrollView.ScrollChangedListener() {
//            @Override
//            public void onScrollChangedListener(int x, int y, int oldX, int oldY) {
//
//            }
//        });

//        scrollview.setOnScrollChangeListener(new View.OnScrollChangeListener() {
//            @Override
//            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
//                Log.d("DDDDD",""+i+"=="+i1+"=="+i2+"=="+i3);
//                mTb.setVisibility(View.VISIBLE);
////                if(i1>=343){
////                    banner.setVisibility(View.GONE);
////                }else{
////                    banner.setVisibility(View.VISIBLE);
////                }
//            }
//        });
        //只进入一次，初始化
        mVp.setAdapter(new FragmentPagerAdapter(getActivity().getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return Lfragments[position];
            }
            @Override
            public int getCount() {
                return Lfragments.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return Ltitles[position];
            }
        });
        mVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //  rl_text.setCurrentTab(position);
                // 切换到当前页面，重置高度
                mVp.requestLayout();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        //绑定
        mTb.setupWithViewPager(mVp);
        mTb.setTabMode(TabLayout.MODE_FIXED);
        //设置默认选中页，宏定义
        mTb.getTabAt(ItemWhat).select();
        mVp.setOffscreenPageLimit(3); //设置向左和向右都缓存的页面个数
        mVp.setCurrentItem(0);
//        mVp.s
        //初始化菜单栏显示
        for (int i = 0; i < mTb.getTabCount(); i++) {
            //寻找到控件
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.tab_items, null);
            LinearLayout mTabView = (LinearLayout) view.findViewById(R.id.item_view);
            TextView mTabText = (TextView) view.findViewById(R.id.item_text);

            mTabText.setText(Ltitles[i]);
//            mTabIcon.setImageResource(Limg[i]);
            //设置不可点击
            // mTabView.setClickable(true);
            //更改选中项样式
            if(i==ItemWhat){
//                mTabIcon.setImageResource(Limgn[i]);
                mTabText.setTextColor(ContextCompat.getColor(getActivity(), R.color.black));
            }

            //设置样式
            mTb.getTabAt(i).setCustomView(view);
        }
        //是否选中监听
        mTb.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //选中时进入，改变样式
                ItemSelect(tab);
                //onTabselected方法里面调用了viewPager的setCurrentItem 所以要想自定义OnTabSelectedListener，也加上mViewPager.setCurrentItem(tab.getPosition())就可以了
                mVp.setCurrentItem(tab.getPosition());
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                //未选中进入，改变样式
                ItemNoSelect(tab);
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                //重新选中
            }
        });


    }

    //某个项选中，改变其样式
    private void ItemSelect(TabLayout.Tab tab) {
        View customView = tab.getCustomView();
        TextView tabText = (TextView) customView.findViewById(R.id.item_text);
        tabText.setTextColor(ContextCompat.getColor(getActivity(), R.color.black));
        String stitle = tabText.getText().toString();
        for(int i=0;i<Ltitles.length;i++){
            if(Ltitles[i].equals(stitle)){
                //Toast.makeText(MainActivity.this,"xxx+"+i,Toast.LENGTH_SHORT).show();
//                tabIcon.setImageResource(Limgn[i]);
            }
        }
    }
    //某个项非选中，改变其样式
    private void ItemNoSelect(TabLayout.Tab tab) {
        View customView = tab.getCustomView();
        TextView tabText = (TextView) customView.findViewById(R.id.item_text);
        tabText.setTextColor(ContextCompat.getColor(getActivity(), R.color.black));
        String stitle = tabText.getText().toString();
        for(int i=0;i<Ltitles.length;i++){
            if(Ltitles[i].equals(stitle)){
//                tabIcon.setImageResource(Limg[i]);
            }
        }
    }

    private void initFragment() {
        mFragmentList = new ArrayList<>();
        mFragmentList.add(NewsFragment.newInstance("新闻"));
        mFragmentList.add(LifeFragment.newInstance("生活"));
        mFragmentList.add(HealthFragment.newInstance("健康"));
        mFragmentList.add(WelfareFragment.newInstance("公益"));
    }

    private ReadFragmentNew initListener() {
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
            }
        });
        banner.setDelayTime(5000);
//        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                getBanner();
//            }
//        });
        tv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openActivity(SysMessageActivity.class);
            }
        });
        return null;
    }

    private void getBanner() {
        RequestParams requestParams = new RequestParams();
        requestParams.put("cat_id", 12);
        HttpUtils.post(Constants.GET_BANNER, requestParams, new onOKJsonHttpResponseHandler<BannerBean>(new TypeToken<Response<BannerBean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//                showToast(throwable.getMessage());
            }

            @Override
            public void onSuccess(int statusCode, Response<BannerBean> datas) {
                if (datas.isSuccess()) {
                    images.clear();
                    images.addAll(datas.getData().getList());
                    List<String> strings = new ArrayList<>();
                    for (int i = 0; i < images.size(); i++) {
                        strings.add(Constants.APP_IP + images.get(i).getImg());
                    }
                    banner.update(strings);
                } else {
                    showToast(datas.getMsg());
                }
//                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
    public void onResume() {
        super.onResume();
        if (!CommonUtils.isNetworkAvailable()) {
            showToast( getResources().getString( R.string.error_network ) );
            return;
        }
        if ("".equals( SPUtils.getStringData( context, "token", "" ) )) {
            return;
        }
    }
}


